//
//  MLWelcomeViewController.swift
//  SinaWeibo
//
//  Created by 李亮亮 on 16/4/9.
//  Copyright © 2016年 Big Fish. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit


class MLWelcomeViewController: UIViewController {

    override func loadView() {
        view = UIImageView(image: UIImage(named: "ad_background"))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 在viewDidLoad阶段获取的根视图的大小可能不是准确的
        
        setupUI()
    }
    
    // 会自动给视图大小重新设置和设备的屏幕尺寸大小一致的size
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 执行动画效果
        animationStart()
    }
    
    // 设置界面
    func setupUI() {
        
        view.addSubview(iconImageView)
        view.addSubview(nameLabel)
        
        iconImageView.cornerRadius = 45
        self.iconImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(view.snp_centerX)
            make.centerY.equalTo(view.snp_bottom).offset(-ScreenHeight*0.3)
            make.size.equalTo(CGSizeMake(90, 90))
        }
        
        self.nameLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(iconImageView.snp_centerX)
            make.top.equalTo(iconImageView.snp_bottom).offset(16)
        }
        
        // 加载头像
        // 网络提供的数据不能够直接使用,需要转换数据(洗数据)
        iconImageView.sd_setImageWithURL(MLUserAccountViewModel.sharedUserAccountViewModel.headImageURL)
        
    }
    
    private func animationStart() {
        // 设置透明
        nameLabel.alpha = 0
        
        let offset = 180 - ScreenHeight
        iconImageView.snp_updateConstraints { (make) in
            // 更新头像的的约束
            make.centerY.equalTo(self.view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: [], animations: {
            // 强制刷新页面 提前刷新页面
            self.view.layoutIfNeeded()
            }) { (_) in
                // 添加文案显示的动画
                UIView.animateWithDuration(0.6, animations: { 
                    // 显示nameLabel
                    self.nameLabel.alpha = 1
                    }, completion: { (_) in
                        // 跳转页面
                        NSNotificationCenter.defaultCenter().postNotificationName(MLSwitchRootViewController, object: "Main")
                })
        }
    }
    
    
    // MARK: 懒加载控件
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    private lazy var nameLabel: UILabel = UILabel(text: (MLUserAccountViewModel.sharedUserAccountViewModel.userAccount?.name ?? ""), textColor: UIColor.darkGrayColor(), fontSize: 16)
    
}
